/**
 * 
 */
package com.leo.book.distributed.chapter04.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Description: 操作原子性-存在安全性问题
 * @author lianliang
 * @date 2017年12月18日 下午4:33:25
 */
public class CountUnsafe {
	public int count = 0;
	
	public final ReentrantLock lock = new ReentrantLock();
	
	static class Job implements Runnable {
		private CountDownLatch countDown;
		private CountUnsafe count;

		public Job(CountUnsafe count, CountDownLatch countDown) {
			this.count = count;
			this.countDown = countDown;
		}

		@Override
		public void run() {
			//synchronized (count) { //synchronized锁
				//count.lock.lock(); //Lock锁
				count.count++;
				countDown.countDown();
				//count.lock.unlock();
			//}
		}
	}

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch countDown = new CountDownLatch(1500);
		CountUnsafe count = new CountUnsafe();
		ExecutorService pool = Executors.newFixedThreadPool(5);
		for (int i = 0; i < 1500; i++) {
			pool.execute(new Job(count, countDown));
		}
		countDown.await();
		System.out.println(count.count);
		pool.shutdown();
	}
}
